import { useCache } from "@/hooks/web/useCache"
import { CacheKey } from "./globalConstants"
import { decrypt, encrypt } from '@/utils/jsencrypt'
import { LoginFromParam } from "@/models/auth/LoginUserModel"
import { TokenInfo } from "@/models/auth/TokenModel"





// 使用缓存
const { wsCache } = useCache()


// 清理当前用户登录信息
const deleteUserCache = () => {
  wsCache.delete(CacheKey.CurrentUser)
  wsCache.delete(CacheKey.RoleRouters)
}

// 获取本地访问token
const getAccessToken = () => {
  const token = wsCache.get(CacheKey.AccessToken)
  if(token) return token
}

// 刷新token
 const getRefreshToken = () => {
  const refreshToken = wsCache.get(CacheKey.RefreshToken)
  if(refreshToken) return refreshToken
}

// 设置token
const setToken = (token: TokenInfo) => {
  wsCache.set(CacheKey.AccessToken, token.AccessToken,{exp: token.ExpiresIn})
  wsCache.set(CacheKey.RefreshToken, token.RefreshToken)
}

// 清理token
const clearToken = () => {
  wsCache.delete(CacheKey.AccessToken)
  wsCache.delete(CacheKey.RefreshToken)
}

// 格式化为jwt token
const formatToken = (token: string): string => {
  return `Bearer ${token}`
}

// 记住登录信息
const setLoginForm = (loginInfo: LoginFromParam) => {
  loginInfo.PassWord = encrypt(loginInfo.PassWord) as string
  wsCache.set(CacheKey.LoginForm, loginInfo,{ exp: 30 * 24 * 60 * 60 })
}

// 获取登录信息
const getLoginForm = ():LoginFromParam => {
  const loginFrm = wsCache.get(CacheKey.LoginForm)
  // debugger
  if (loginFrm) {
    loginFrm.PassWord = decrypt(loginFrm.PassWord) as string
  }
  return loginFrm as LoginFromParam
}

// 清理登录信息
const clearLoginForm = () => {
  wsCache.delete(CacheKey.LoginForm)
}

// 写入本地缓存
const writeCache = (data: any, key: string,exp?:number) => {
  wsCache.set(key, data,{exp})
}

// 读取本地缓存
const readCache = (key: string):any => {
  return wsCache.get(key)
}

// 清除指定key缓存
const deleteCache = (key: string) => {
  return wsCache.delete(key)
}

export default {
  deleteUserCache,
  getRefreshToken,
  getAccessToken,
  clearToken,
  setToken,
  formatToken,
  getLoginForm,
  setLoginForm,
  clearLoginForm,
  writeCache,
  readCache,
  deleteCache
}
